#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
TikTok Shop 退货管理API接口
通过逆向分析获取的退货订单列表接口
"""

import requests
import json
import time
from datetime import datetime, timedelta
from typing import Dict, List, Optional


class TikTokShopReturnAPI:
    """TikTok Shop 退货管理API类"""
    
    def __init__(self, cookie: str, seller_id: str = "7496208812426365551"):
        """
        初始化API
        
        Args:
            cookie: 登录cookie
            seller_id: 卖家ID，默认为7496208812426365551
        """
        self.base_url = "https://api16-normal-sg.tiktokshopglobalselling.com"
        self.cookie = cookie
        self.seller_id = seller_id
        self.session = requests.Session()
        
        # 设置请求头
        self.headers = {
            'authority': 'api16-normal-sg.tiktokshopglobalselling.com',
            'accept': 'application/json, text/plain, */*',
            'accept-language': 'zh-CN,zh;q=0.9',
            'agw-js-conv': 'str',
            'content-type': 'application/json',
            'cookie': self.cookie,
            'origin': 'https://seller.tiktokshopglobalselling.com',
            'referer': 'https://seller.tiktokshopglobalselling.com/',
            'sec-ch-ua': '"Google Chrome";v="125", "Chromium";v="125", "Not.A/Brand";v="24"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
            'sec-fetch-dest': 'empty',
            'sec-fetch-mode': 'cors',
            'sec-fetch-site': 'same-site',
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36'
        }
    
    def get_timestamp(self, days_ago: int = 3) -> Dict[str, str]:
        """
        获取时间戳
        
        Args:
            days_ago: 几天前的时间
            
        Returns:
            包含开始和结束时间戳的字典
        """
        end_time = datetime.now()
        start_time = end_time - timedelta(days=days_ago)
        
        # 转换为毫秒时间戳
        start_timestamp = int(start_time.timestamp() * 1000)
        end_timestamp = int(end_time.timestamp() * 1000)
        
        return {
            'create_begin_time': str(start_timestamp),
            'create_end_time': str(end_timestamp)
        }
    
    def list_return_orders(self, 
                          page_no: int = 1, 
                          page_size: int = 10,
                          status_list: List[int] = None,
                          days_ago: int = 3) -> Dict:
        """
        获取退货订单列表
        
        Args:
            page_no: 页码
            page_size: 每页大小
            status_list: 状态列表 [2,3,4,5,6,7,8,9]
            days_ago: 查询几天前的数据
            
        Returns:
            API响应数据
        """
        if status_list is None:
            status_list = [2, 3, 4, 5, 6, 7, 8, 9]
        
        # 构建请求URL
        url = f"{self.base_url}/bff/scs/supplier-synergy/return/list-return-order"
        params = {
            'aid': '6556',
            'locale': 'zh-CN',
            'oec_seller_id': self.seller_id,
            'timezone_offset': '-480',
            '_': str(int(time.time() * 1000))
        }
        
        # 获取时间范围
        time_range = self.get_timestamp(days_ago)
        
        # 构建请求体
        payload = {
            'need_fields': [1, 2],
            'option': {
                'status_list': status_list,
                'create_begin_time': time_range['create_begin_time'],
                'create_end_time': time_range['create_end_time'],
                'direction': 2,
                'order_by': 1,
                'problem_tag_code_list': [],
                'with_confirming_tab_count': True,
                'with_count': True
            },
            'page_info': {
                'page_no': page_no,
                'page_size': page_size
            }
        }
        
        try:
            response = self.session.post(
                url,
                params=params,
                headers=self.headers,
                json=payload,
                timeout=30
            )
            
            response.raise_for_status()
            
            return response.json()
            
        except requests.exceptions.RequestException as e:
            print(f"请求失败: {e}")
            return {'error': str(e)}
    


def main(cookie):
  
    if cookie == "您的cookie":
        print("请先设置您的cookie")
        return
    
    # 创建API实例
    api = TikTokShopReturnAPI(cookie)
    
    result = api.list_return_orders(page_no=1, page_size=100)
    
    return result


if __name__ == "__main__":
    result = main(r"_ga=GA1.1.900545957.1752060090; _ga_BZBQ2QHQSP=GS2.1.s1752066327$o2$g0$t1752066327$j0$l0$h6808533; msToken=hZtcqBRwu7CDlV3UDlo7VXujS0iu7n4Sxmi7Fkwc9i-fBA3d-zpgYYqpr42L13dHGeSzDEeyV2F75w0idosrDVm09sXoGx15qIa_hCz8xmRF9Ya_szIX5IP9m28mIVuedZn1cUA=; passport_csrf_token=14170785e93d08fde006fb4c98b99b03; passport_csrf_token_default=14170785e93d08fde006fb4c98b99b03; i18next=zh-CN; store-country-sign=MEIEDHcgwxJAWbnEoxvUdQQgTTCwgaQiUZqLzxeeOpibM9en0L-vTxw4gYzlLOTX21EEEOIOoaYt3IdVkGCT1RtYYAc; ATLAS_LANG=zh-CN; d_ticket=56080974c70d273c67911c6a55118c0e4a248; gs_seller_type_for_report=full-service; gs_page_type=mmo; _m4b_theme_=new; s_v_web_id=verify_mhhoh2ua_Dywr6k3N_kcD2_4Qjs_AvaX_TrRMmiNONo07; odin_tt=cc0c1a9598ef4296a66eca3d2ef0b9663f61d90fd7483b5a09997f4e552977956ff8adb6b968c13ce15744181b67a1c744bd36e99c0b072ae036971a16abec1b; passport_auth_status=e7827ccd18b8d057b20165bc0162a1f6%2C5eba9b5b7c2e097a5ea26ea699950342; passport_auth_status_ss=e7827ccd18b8d057b20165bc0162a1f6%2C5eba9b5b7c2e097a5ea26ea699950342; uid_tt=df17b6603293c7f879cfb2711944abe2197b7d8263e0d3f5f2f1ca2fd13c4882; uid_tt_ss=df17b6603293c7f879cfb2711944abe2197b7d8263e0d3f5f2f1ca2fd13c4882; sid_tt=b1015741f6ae5f37cfb933a13dca97a6; sessionid=b1015741f6ae5f37cfb933a13dca97a6; sessionid_ss=b1015741f6ae5f37cfb933a13dca97a6; msToken=VZl6Ymkd97J-iDnNR2rhjTx5Zs84J-_O4xhocUgUAh5VRxFYbekmzO_bM55uJ3cfeC0M0Yv6bydlU9hNVYNcdZ2b7NuL-CCWF0GUcLOEj4j3petVkVVVpwoR4qe8v3aruYDX9Sg=; global_seller_id_unified_seller_env=7496208812426365551; app_id_unified_seller_env=6556; oec_seller_id_unified_seller_env=7496208812426365551; user_oec_info=0a53d767b7e9b7eebd14120ee4cb6e630481daaa21152043468783cee98ef080496c5f064cd97761d88283b3fc130ab350529b6e2f2409f6136f05ccee6ef5ba4e0f1e146a98c6144414ea2b0db71c0878615a18201a490a3c000000000000000000004faa9a93af3dc5d5d24b73d6632a18b7e2dbd5f426161e5dd277df95988ed875e6f245f34aa02186efb4563c85476b8cc31d1092bd800e1886d2f6f20d22010484e238e3; ttwid=1%7Ck2d5DDBUxcRgeASau2IL4F1vOLnQAGyakoO6efjjg0U%7C1762085966%7Cbeb6aa4fef568a92a37584771895936689efce5d6047d0ea66001e3322af31b4; goofy_grayscale_uid=986bfc58babcaca9fc7a835a0033fce0; test_flag=0; sid_guard=b1015741f6ae5f37cfb933a13dca97a6%7C1762144278%7C259200%7CThu%2C+06-Nov-2025+04%3A31%3A18+GMT; tt_session_tlb_tag=sttt%7C2%7CsQFXQfauXzfPuTOhPcqXpv________-06bq4jiJRJEFJbvrSC5fezut4UjzsrsezgJy3nILMmQE%3D; sid_ucp_v1=1.0.0-KGNhNDI2YjhlNTIwZTNkMjE4MzIzYjBjZjhmOWRhNTc5YjI0ZmE0OTUKHQiRiIy61tTvtWgQluCgyAYYnDMgDDDB_a7DBjgIEAMaAm15IiBiMTAxNTc0MWY2YWU1ZjM3Y2ZiOTMzYTEzZGNhOTdhNg; ssid_ucp_v1=1.0.0-KGNhNDI2YjhlNTIwZTNkMjE4MzIzYjBjZjhmOWRhNTc5YjI0ZmE0OTUKHQiRiIy61tTvtWgQluCgyAYYnDMgDDDB_a7DBjgIEAMaAm15IiBiMTAxNTc0MWY2YWU1ZjM3Y2ZiOTMzYTEzZGNhOTdhNg; passport_fe_beating_status=true; gd_random=eyJtYXRjaCI6dHJ1ZSwicGVyY2VudCI6MC4xMDY2NTI5MDc5OTE5NTIyNn0=.ZQvRuq/KBYPjx8RgFX49lx+yTK25X8pfvRmLf91Nzrc=")
    all_data = []
    for i in result["data"]["data"]["order_list"]:

        new_data = [
            {
                "request_count": item["request_count"],
                "sku_code": item["sku_code"]
            }
            for item in i["return_item_list"]
        ]
        all_data.append((i["source_order_code"],i["relative_order_code"],i["external_code"],new_data))
    print(all_data)
